<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/04/18 20:39:40 $)
// $RCSfile: functions_language.php,v $ : $Revision: 1.17 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}


/**
* Imports the master language file
*/
function importLanguageFromFile($filename, $ismaster = false, $isdefault = false, $displayorder = 0, $versioncheck = false)
{
	global $_SETUP, $_SWIFT, $xml, $dbCore, $datastore;

	// Parse the templates XML File.
	$xmllanguage = $xml->xml2tree(implode("", file($filename)));

	if (!is_array($xmllanguage))
	{
		return false;
	}

	$finallanguage = &$xmllanguage["swiftlanguage"][0]["children"];
	$title = $finallanguage["title"][0]["values"][0];
	$isocode = $finallanguage["isocode"][0]["values"][0];
	$author = $finallanguage["author"][0]["values"][0];
	$charset = $finallanguage["charset"][0]["values"][0];
	$version = $finallanguage["version"][0]["values"][0];

	if (!empty($version) && $versioncheck == true)
	{
		// check for version
		if (version_compare($version, SWIFTVERSION) == -1)
		{
			return -1;
		}
	}
	
	if (empty($title))
	{
		return false;
	}

	if (strtoupper($finallanguage["textdirection"][0]["values"][0]) == "RTL")
	{
		$direction = "rtl";
	} else {
		$direction = "ltr";
	}

	// Delete the current master language file if we are inserting a new one
	if ($ismaster)
	{
		$languageidlist = array();

		// Get all the master languages
		$dbCore->query("SELECT `languageid` FROM `". TABLE_PREFIX ."languages` WHERE `ismaster` = '1';");
		while ($dbCore->nextRecord())
		{
			$languageidlist[] = $dbCore->Record["languageid"];
		}

		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."languages` WHERE `languageid` IN (". buildIN($languageidlist) .");");
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."languagephrases` WHERE `languageid` IN (". buildIN($languageidlist) .");");

	}

	// Are we supposed to set this language as default?
	if ($isdefault)
	{
		$dbCore->query("UPDATE `". TABLE_PREFIX ."languages` SET `isdefault` = '0';");
	}

	if (empty($displayorder))
	{
		$_total = $dbCore->queryFetch("SELECT COUNT(*) AS totalitems FROM `". TABLE_PREFIX ."languages`;");
		$displayorder = $_total["totalitems"]+1;
	}

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."languages` (`title`, `languagecode`, `charset`, `author`, `textdirection`, `ismaster`, `isdefault`, `displayorder`) VALUES('". $dbCore->escape($title) ."', '". $dbCore->escape($isocode) ."', '". $dbCore->escape($charset) ."', '". $dbCore->escape($author) ."', '". $direction ."', '". iif($ismaster==true, "1", "0") ."', '". iif($isdefault==true, "1", "0") ."', '". $dbCore->escape($displayorder) ."');");
	$languageid = $dbCore->lastInsertId();

	$cnt = 0;
	$phrasequerylist = $_sql = array();
//	echo "Total Phrases: ".count($finallanguage["phrase"])."<BR />";
	for ($kk=0; $kk<count($finallanguage["phrase"]); $kk++)
	{
		$cnt++;
		$phrase = $finallanguage["phrase"][$kk]["attrs"];
		$contents = $finallanguage["phrase"][$kk]["values"][0];
		if ($phrase["code"] == "charset")
		{
			continue;
		}
		// We add 20 phrases at a time
//		echo "Processing Phrase: ".$phrase["code"]."<BR />";
		$_sql[] = "('". intval($languageid) ."', '". $dbCore->escape($phrase["section"]) ."', '". $dbCore->escape($phrase["code"]) ."', '". $dbCore->escape($phrase["section"].":".$phrase["code"]) ."','". $dbCore->escape($contents) ."')";
		if ($cnt >= 20 || ($kk+1) == count($finallanguage["phrase"]))
		{
			$cnt = 0;
			//(ceil($kk/250)-1)
	//		echo "Inserting Phrases: ".count($_sql)."<BR />";
			$queryresult = $dbCore->query("INSERT INTO `". TABLE_PREFIX ."languagephrases` (`languageid`, `section`, `code`, `sectioncode`, `contents`) VALUES ".implode(",", $_sql).";", 2);
			if (!$queryresult)
			{
				echo $dbCore->fetchLastError();
				echo "Failed to Insert Phrases..".implode("<BR />", $_sql)."<BR />";
				exit;
			}
			$_sql = array();
		}
	}

	if (count($_sql) != "")
	{
		$phrasequerylist[] = "INSERT INTO `". TABLE_PREFIX ."languagephrases` (`languageid`, `section`, `code`, `sectioncode`, `contents`) VALUES ".implode(",", $_sql).";";
		$queryadd = "";
	}

	$phrasequerylist[] = "INSERT INTO `". TABLE_PREFIX ."languagephrases` (`languageid`, `section`, `code`, `sectioncode`, `contents`) VALUES('". intval($languageid) ."', 'default', 'charset', 'default:charset', '". $dbCore->escape($charset). "');";

//	echo "Processing Phrase Later: ".count($_sql)."<BR />";
	foreach ($phrasequerylist as $key=>$val)
	{
		$queryresult = $dbCore->query($val, 2);
		if (!$queryresult)
		{
			echo $dbCore->fetchLastError();
			echo "Failed to run Insert Phrases Query..".$val."<BR />";
			exit;
		}
	}

	$result["languageid"] = $languageid;
	$result["title"] = $title;
//	exit;

	return $result;
}

/**
* Merges the phrases of given language with the ones in the provided xml
*/
function mergeLanguageFromFile($languageid, $filename, $versioncheck = false, $isupgrade = false)
{
	global $dbCore, $xml, $_SWIFT, $datastore;

	// Get the current language data
	$_language = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."languages` WHERE `languageid` = '". intval($languageid) ."';");
	if (empty($_language["languageid"]))
	{
		return false;
	}

	// Parse the templates XML File.
	$xmllanguage = $xml->xml2tree(implode("", file($filename)));

	if (!is_array($xmllanguage))
	{
		return false;
	}

	$finallanguage = &$xmllanguage["swiftlanguage"][0]["children"];
	$title = $finallanguage["title"][0]["values"][0];
	$isocode = $finallanguage["isocode"][0]["values"][0];
	$author = $finallanguage["author"][0]["values"][0];
	$charset = $finallanguage["charset"][0]["values"][0];
	$version = $finallanguage["version"][0]["values"][0];

	if (!empty($version) && $versioncheck == true)
	{
		// check for version
		if (version_compare($version, SWIFTVERSION) == -1)
		{
			return -1;
		}
	}

	if (empty($title))
	{
		return false;
	}

	if (strtoupper($finallanguage["textdirection"][0]["values"][0]) == "RTL")
	{
		$direction = "rtl";
	} else {
		$direction = "ltr";
	}

	// Now fetch the phrases for the language with which we are about to merge
	$dbphraselist = $dbsectionlist = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."languagephrases` WHERE `languageid` = '". intval($languageid) ."';");
	while ($dbCore->nextRecord())
	{
		$dbphraselist[$dbCore->Record["sectioncode"]] = $dbCore->Record["contents"];
	}

	// Build the xml phrase list
	$cnt = 0;
	$phraselist = $phrasesql = array();
	for ($kk=0; $kk<count($finallanguage["phrase"]); $kk++)
	{
		$cnt++;
		$phrase = $finallanguage["phrase"][$kk]["attrs"];
		$contents = $finallanguage["phrase"][$kk]["values"][0];
		$pointer = &$dbphraselist[$phrase["section"].":".$phrase["code"]];
		if ($phrase["code"] == "charset")
		{
			continue;
		}

		if (($pointer != $contents && $isupgrade == false) || empty($pointer))
		{
			// Phrase doesnt match.. we need to replace/insert it
			$phrasesql[] = "('". intval($languageid) ."', '". $dbCore->escape($phrase["code"]) ."', '". $dbCore->escape($phrase["section"]) ."', '". $dbCore->escape($phrase["section"].":".$phrase["code"]) ."', '". $dbCore->escape($contents) ."')";
		}
		unset($pointer);
	}

	if (_is_array($phrasesql))
	{
		$queryresult = $dbCore->query("REPLACE INTO `". TABLE_PREFIX ."languagephrases` (`languageid`, `code`, `section`, `sectioncode`, `contents`) VALUES ". implode(", ", $phrasesql) .";");

		if (!$queryresult)
		{
			echo $dbCore->fetchLastError();
			echo "Failed to Insert Phrases..".implode("<BR />", $phrasesql)."<BR />";
			exit;
		}
	}
	
	return 1;
}

/**
* Inserts a new phrase for given language
*/
function insertPhrase($languageid, $phrasecode, $phrasevalue)
{
	global $dbCore;

	$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."languagephrases` (`languageid`, `code`, `section`, `sectioncode`, `contents`) VALUES ('". intval($languageid) ."', '". $dbCore->escape($phrasecode) ."', '". "default" ."', 'default:". $dbCore->escape($phrasecode) ."', '". $dbCore->escape($phrasevalue) ."')");

	rebuildPhraseCache($languageid);

	return true;
}

/**
* Deletes a given phrase
*/
function deletePhrase($phraseid)
{
	global $dbCore;

	$_phrase = $dbCore->queryFetch("SELECT `code`, `languageid` FROM `". TABLE_PREFIX ."languagephrases` WHERE `phraseid` = '". intval($phraseid) ."';");
	if (empty($_phrase["languageid"]))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."languagephrases` WHERE `phraseid` = '". intval($phraseid) ."';");

	rebuildPhraseCache($_phrase["languageid"]);

	return $_phrase["code"];
}

/**
* Updates phrases for given language
*/
function updatePhrases($languageid, $phraselist)
{
	global $dbCore, $_SWIFT;

	if (!is_array($phraselist) || !count($phraselist))
	{
		return false;
	}

	$finalphraselist = array_keys($phraselist);

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."languagephrases` WHERE `languageid` = '". intval($languageid) ."' AND `code` IN (". buildIN($finalphraselist) .");");
	while ($dbCore->nextRecord())
	{
		$phrasesql[] = "('". intval($languageid) ."', '". $dbCore->escape($dbCore->Record["code"]) ."', '". $dbCore->escape($dbCore->Record["section"]) ."', '". $dbCore->escape($phraselist[$dbCore->Record["code"]]) ."')";		
	}

	$dbCore->query("REPLACE INTO `". TABLE_PREFIX ."languagephrases` (`languageid`, `code`, `section`, `contents`) VALUES ". implode(", ", $phrasesql) .";");

	rebuildPhraseCache($languageid);

	return true;
}

/**
* Rebuild the language phrase cache
*/
function rebuildPhraseCache($languageid)
{
	global $dbCore, $datastore;

	$_language = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."languages` WHERE `languageid` = '". intval($languageid) ."';");

	if (empty($_language["languageid"]))
	{
		return false;
	}

	$isocode = $_language["languagecode"];
	$phrasestore = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."languagephrases` WHERE `languageid` = '". intval($languageid) ."' ORDER BY `phraseid` ASC;");
	while ($dbCore->nextRecord())
	{
		$phrasestore[$dbCore->Record["section"]][$dbCore->Record["code"]] = $dbCore->Record["contents"];
	}

	foreach ($phrasestore as $key=>$val)
	{
		$datastore->update($isocode.":".$key, $val);
	}
}

/**
* Rebuilds the language cache
*/
function rebuildLanguageCache()
{
	global $dbCore, $_SWIFT, $datastore;
	
	$languagecache = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."languages` ORDER BY `displayorder` ASC;");
	while ($dbCore->nextRecord())
	{
		$languagecache[$dbCore->Record["languageid"]] = $dbCore->Record;
	}
	

	$datastore->update("languagecache", $languagecache);
}

/**
* Gets the display order number for the next insert
*/
function getLastLanguageDisplayOrder()
{
	global $_SWIFT, $dbCore, $datastore;

	$datastore->load("languagecache");

	// Get Last Insert ID
	$linsertid = max(array_keys($_SWIFT["languagecache"]));
	
	$disporder = $_SWIFT["languagecache"][$linsertid]["displayorder"]+1;
	return $disporder;
}

/**
* Gets the languageid of Master Language
*/
function getMasterLanguageID()
{
	global $_SWIFT, $datastore;

	$datastore->load("languagecache");

	foreach ($_SWIFT["languagecache"] as $key=>$val)
	{
		if ($val["ismaster"] == 1)
		{
			return $val["languageid"];
		}
	}

	return false;	
}

/**
* Insert a new language
*/
function insertNewLanguage($title, $author, $isdefault, $textdirection, $languagecode, $charset, $displayorder)
{
	global $_SWIFT, $dbCore;

	// Get master language
	$masterlanguageid = getMasterLanguageID();
	if (!$masterlanguageid)
	{
		return false;
	}

	// Is this supposed to be the default language?
	if ($isdefault == true)
	{
		$dbCore->query("UPDATE `". TABLE_PREFIX ."languages` SET `isdefault` = '0';");
	}

	// First insert the language record
	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."languages` (`title`, `languagecode`, `charset`, `author`, `textdirection`, `ismaster`, `isdefault`, `displayorder`) VALUES ('". $dbCore->escape($title) ."', '". $dbCore->escape($languagecode) ."', '". $dbCore->escape($charset) ."', '". $dbCore->escape($author) ."', '". iif(strtoupper($textdirection)=="RTL", "rtl", "ltr") ."', '0', '". iif($isdefault==true, "1", "0") ."', '". $dbCore->escape($displayorder) ."');");
	$languageid = $dbCore->lastInsertId();

	// Do a fetch for all phrases of master language
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."languagephrases` WHERE `languageid` = '". intval($masterlanguageid) ."';");
	while ($dbCore->nextRecord())
	{
		$queryadd .= ",('". intval($languageid) ."', '". $dbCore->escape($dbCore->Record["section"]) ."', '". $dbCore->escape($dbCore->Record["code"]) ."', '". $dbCore->escape($dbCore->Record["sectioncode"]) ."','". $dbCore->escape($dbCore->Record["contents"]) ."')";
	}

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."languagephrases` (`languageid`, `section`, `code`, `sectioncode`, `contents`) VALUES".substr($queryadd, 1, strlen($queryadd)));

	rebuildLanguageCache();
	rebuildPhraseCache($languageid);

	return $languageid;
}

/**
* Update the given language
*/
function updateLanguage($languageid, $title, $author, $isdefault, $textdirection, $languagecode, $charset, $displayorder)
{
	global $dbCore;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."languages` SET `title` = '". $dbCore->escape($title) ."', languagecode = '". $dbCore->escape($languagecode) ."', charset = '". $dbCore->escape($charset) ."', author = '". $dbCore->escape($author) ."', textdirection = '". iif(strtoupper($textdirection)=="RTL", "rtl", "ltr") ."', isdefault = '". iif($isdefault==true, "1", "0") ."', displayorder = '". $dbCore->escape($displayorder) ."' WHERE `languageid` = '". intval($languageid) ."';");

	rebuildLanguageCache();
	rebuildPhraseCache($languageid);
}

/**
* Deletes the given languages and their phrases
*/
function deleteLanguages($languageidlist)
{
	global $dbCore, $_SWIFT, $datastore, $registry;

	if (!is_array($languageidlist) || !count($languageidlist))
	{
		return false;
	}

	// Registry cleanup
	$sectionlist = $keydumplist = array();
	$dbCore->query("SELECT DISTINCT(`section`) FROM `". TABLE_PREFIX ."languagephrases`");
	while ($dbCore->nextRecord())
	{
		$sectionlist[] = $dbCore->Record["section"];
	}

	// iterate through the languages and make sure we arent deleting the master language
	$datastore->load("languagecache");
	foreach ($_SWIFT["languagecache"] as $key=>$val)
	{
		if (in_array($val["languageid"], $languageidlist) && $val["ismaster"] == true)
		{
			// woops!.. no go.. nuke that value
			$newarray = array_flip($languageidlist);
			unset($newarray[$val["languageid"]]);
			$languageidlist = array_flip($newarray);
		} else if (in_array($val["languageid"], $languageidlist)) {
			// For all the sections we have.. make a key delete list
			for ($ii=0; $ii<count($sectionlist); $ii++)
			{
				$dumpkey = $val["languagecode"].":".$sectionlist[$ii];
				if (!in_array($dumpkey, $keydumplist))
				{
					$keydumplist[] = $dumpkey;					
				}
			}
		}
	}
	$registry->deleteKeyList($keydumplist);


	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."languages` WHERE `languageid` IN (". buildIN($languageidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."languagephrases` WHERE `languageid` IN (". buildIN($languageidlist) .");");

	rebuildLanguageCache();
	rebuildPhraseCache($languageid);
	return true;
}

/**
* Renders language form for edit/insert
*/
function renderLanguageForm($type)
{
	global $_SWIFT;

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["languagedetails"]);

	printTextRow("title", $_SWIFT["language"]["languagetitle"], $_SWIFT["language"]["desc_languagetitle"], "text", $_POST["title"]);

	printTextRow("author", $_SWIFT["language"]["authorname"], $_SWIFT["language"]["desc_authorname"], "text", $_POST["author"]);

/*	if ($_POST["isdefault"] == 1 && $type == EDIT)
	{
		addHiddenField("isdefault", "1");		
	} else {
		printYesNoRow("isdefault", $_SWIFT["language"]["isdefault"], $_SWIFT["language"]["desc_isdefault"], iif(empty($_POST["isdefault"]), false, $_POST["isdefault"]));		
	}*/

	$options[0]["title"] = $_SWIFT["language"]["ltr"];
	$options[0]["value"] = "ltr";
	$options[1]["title"] = $_SWIFT["language"]["rtl"];
	$options[1]["value"] = "rtl";

	printSelectRow("textdirection", $_SWIFT["language"]["textdirection"], $_SWIFT["language"]["desc_textdirection"], $options);

	printTextRow("languagecode", $_SWIFT["language"]["isocode"], $_SWIFT["language"]["desc_isocode"], "text", $_POST["languagecode"]);

	printTextRow("charset", $_SWIFT["language"]["languagecharset"], $_SWIFT["language"]["desc_languagecharset"], "text", $_POST["charset"]);

	printNumberRow("displayorder", $_SWIFT["language"]["displayorder"], $_SWIFT["language"]["desc_displayorder"], iif($_POST["displayorder"] != "", $_POST["displayorder"], getLastLanguageDisplayOrder()));

	printSubmitRow(iif($type==INSERT,$_SWIFT["language"]["insertlanguage"], $_SWIFT["language"]["update"]));

	printMainTableFooter();

	addHiddenField("_m", "core");
	addHiddenField("_a", iif($type==INSERT, "insertlanguage", "editlanguage"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("languageid", $_POST["languageid"]);
	}
	printFormEnd();
}

/**
* Generates the language file name using product name and version
*/
function generateLanguageFilename($languagetitle)
{
	return strtolower(SWIFTPRODUCT).".".str_replace(".", "-", SWIFTVERSION).".". strtolower(cleanVar($languagetitle)) .".language.xml";
}

/**
* Exports the language xml file
*/
function doExportLanguage($languageid, $filename = "")
{
	global $dbCore, $xml, $_SWIFT;

	$_language = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."languages` WHERE `languageid` = '". intval($languageid) ."';");
	if (empty($_language["languageid"]))
	{
		return false;
	}

	if (empty($filename))
	{
		$filename = generateLanguageFilename($_language["title"]);
	}

	if (function_exists("set_time_limit") && !ini_get("safe_mode"))
	{
		@set_time_limit(1500);
	}

	$xml->addComment(sprintf($_SWIFT["language"]["generationdate"], edate($_SWIFT["settings"]["dt_datetimeformat"], DATENOW)));
	$xml->addParentTag("swiftlanguage");
		$xml->addTag("title", $_language["title"]);
		$xml->addTag("isocode", $_language["languagecode"]);
		$xml->addTag("author", $_language["author"]);
		$xml->addTag("charset", $_language["charset"]);
		$xml->addTag("textdirection", strtoupper($_language["textdirection"]));
		$xml->addTag("version", SWIFTVERSION);

		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."languagephrases` WHERE `languageid` = '". intval($languageid) ."' ORDER BY `phraseid` ASC;");
		while ($dbCore->nextRecord())
		{
			$xml->addTag("phrase", $dbCore->Record["contents"], array("section" => $dbCore->Record["section"], "code" => $dbCore->Record["code"]));
		}

	$xml->endTag("swiftlanguage");

	$xmldata = $xml->returnXML();

	if(isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
		// IE Bug in download name workaround
		ini_set( 'zlib.output_compression','Off' );
	}

	header("Content-Type: application/force-download");

	if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")){
		header("Content-Disposition: attachment; filename=\"". $filename ."\"");
	} else{
		header("Content-Disposition: attachment; filename=\"". $filename ."\"");
	}

	header("Content-Transfer-Encoding: binary\n");
	header("Content-Length: ". strlen($xmldata) ."\n");
	echo $xmldata;
}
?>